package com.example.framework509.codeGen.utils;

import com.example.framework509.codeGen.entity.middlePojp.EntityContainer;
import com.example.framework509.codeGen.entity.middlePojp.FieldContainer;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SqlUtil {

    public String createSql(EntityContainer entityInfo) {
        StringBuilder sql = new StringBuilder();
        String tableName = StringUtil.toUnderScoreCase(entityInfo.getModelName()) + "_" + StringUtil.toUnderScoreCase(entityInfo.getEntityName());
        sql.append("CREATE TABLE `").append(tableName);
        //字段
        sql.append("` ( `id` int NOT NULL AUTO_INCREMENT, ");
        List<FieldContainer> fields = entityInfo.getProps();
        for (FieldContainer field : fields) {
            switch (field.getNameUnder()) {
                case "creator":
                    sql.append("  `creator` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, ");
                    continue;
                case "create_time":
                    sql.append("  `create_time` datetime DEFAULT CURRENT_TIMESTAMP, ");
                    continue;
                case "editor":
                    sql.append("  `editor` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, ");
                    continue;
                case "edit_time":
                    sql.append("  `edit_time` datetime DEFAULT CURRENT_TIMESTAMP, ");
                    continue;
            }
            sql.append("`");
            //字段名称
            sql.append(field.getNameUnder()).append("` ");
            //字段类型
            sql.append(getJdbcType(field.getDataType())).append(getJdbcType(field.getDataType()).equals("varchar") ? "(" + field.getLength() + ") CHARACTER SET utf8 COLLATE utf8_general_ci " : " ");
            //允许空
            sql.append(field.getAnnotations().contains("AllowNull") ? "" : "NOT NULL ").append("COMMENT '");
            //字段备注
            sql.append(field.getRemark()).append("', ");
        }
        sql.append("  `is_deleted` datetime DEFAULT NULL, " +
                "  `version` int NOT NULL DEFAULT '1', " +
                "  PRIMARY KEY (`id`) " +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
        return sql.toString();
    }


    private String getJdbcType(String javaType) {
        String jdbcType;
        switch (javaType) {
            case "String":
                jdbcType = "varchar";
                break;
            case "Integer":
                jdbcType = "int";
                break;
            case "Double":
                jdbcType = "double";
                break;
            case "Boolean":
                jdbcType = "boolean";
                break;
            case "DateTime":
                jdbcType = "datetime";
                break;
            default:
                jdbcType = "varchar";
                break;
        }
        return jdbcType;
    }

}
